//
//  BaseRequest.m
//  Learn
//
//  Created by icomexe on 2018/10/27.
//  Copyright © 2018年 cjg. All rights reserved.
//

#import "BaseRequest.h"
#import "BaseHttpManager.h"
#import "BaseRequestApi.h"

@implementation BaseRequest

#pragma mark -- post请求
//post带数据请求 -- 1.请求地址 2.是否缓存 3.超时loading 4.参数 5.数据 6. 结果
+ (void)basePOST:(NSString *)url cache:(BOOL)cache autoHideLoading:(BOOL)hide parms:(id)parms data:(NSData *)data result:(BaseResultBlock)resultBlock {
    
    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
            [[BaseHttpManager defaultManager].sessionManager POST:url parameters:parms headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                //上传到服务器的数据
                if (data) {
                    //上传的参数(上传图片，以文件流的格式)
                    [formData appendPartWithFileData:data
                                                name:@"headPortrait"
                                            fileName:@"headImage.jpg"
                                            mimeType:@"image/jpg"];
                }
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self requestLog:task parms:parms responseObject:responseObject error:nil];
                resultBlock(responseObject,nil);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self requestLog:task parms:parms responseObject:nil error:nil];
                resultBlock(nil,error);
            }];
        }else {
            
        }
    }];
}

//post常规请求 -- 1.请求地址 2.是否缓存 3.超时loading 4.参数 5. 结果
+ (void)basePOST:(NSString *)url cache:(BOOL)cache autoHideLoading:(BOOL)hide parms:(id)parms result:(BaseResultBlock)resultBlock {
    
    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) {
            [[BaseHttpManager defaultManager] configureRequestSerializer];
            NSDictionary *header = lApp.useModel.token?@{@"token":lApp.useModel.token} :nil;
            [[BaseHttpManager defaultManager].sessionManager POST:url parameters:parms headers:header progress:^(NSProgress * _Nonnull uploadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self requestLog:task parms:parms responseObject:responseObject error:nil];
                resultBlock(responseObject , nil);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self requestLog:task parms:parms responseObject:nil error:nil];
                resultBlock(nil, error);
            }];
        }else {
            
        }
    }];
    
}

//post后台返回非json请求 -- 1.请求地址 2.是否缓存 3.超时loading 4.参数 5. 结果
+ (void)basePOST_New:(NSString *)url cache:(BOOL)cache autoHideLoading:(BOOL)hide parms:(id)parms result:(BaseResultBlock)resultBlock {
   
    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) {
           
            [[BaseHttpManager defaultManager] configureRequestSerializerNew];
            [[BaseHttpManager defaultManager].sessionManager POST:url parameters:parms headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self requestLog:task parms:parms responseObject:responseObject error:nil];
                resultBlock(responseObject,nil);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self requestLog:task parms:parms responseObject:nil error:error];
                resultBlock(nil,error);
            }];

        }else {
            
        }
    }];
}

#pragma mark -- get请求
//get请求后台返回json类型 ---- 1.请求地址 2.是否缓存 3.超时loading 4.参数 5. 结果
+ (void)baseGET:(NSString *)url cache:(BOOL)cache autoHideLoading:(BOOL)hide parms:(id)parms request:(BaseResultBlock)resultBlock {
    
    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) {
            [[BaseHttpManager defaultManager] configureRequestSerializer];
            [[BaseHttpManager defaultManager].sessionManager GET:url parameters:parms headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self requestLog:task parms:parms responseObject:responseObject error:nil];
                resultBlock(responseObject , nil);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self requestLog:task parms:parms responseObject:nil error:error];
                resultBlock(nil , error);
            }];
            
        }else {
            
        }
    }];
}

//get请求后台返回非json类型 --- 1.请求地址 2.是否缓存 3.超时loading 4.参数 5. 结果
+ (void)baseGET_New:(NSString *)url cache:(BOOL)cache autoHideLoading:(BOOL)hide parms:(id)parms request:(BaseResultBlock)resultBlock {
   
    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) {
            [[BaseHttpManager defaultManager] configureRequestSerializerNew];
            [[BaseHttpManager defaultManager].sessionManager GET:url parameters:parms headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self requestLog:task parms:parms responseObject:nil error:error];
                resultBlock(nil , error);
            }];
            
        }else {
            
        }
    }];

}

#pragma mark --- 下载
+ (void)baseDownLoad:(NSString *)url cache:(BOOL)cache autoHideLoading:(BOOL)hide parms:(id)parms progess:(BaseProgressBlock)progressBlock result:(BaseResultBlock)resultBlock {
}

#pragma  mark --- 上传文件
+ (void)baseUpload:(NSString *)url parms:(id)parms imageList:(NSArray <UIImage *> *)imageList cache:(BOOL)cache autoHideLoading:(BOOL)hide progress:(BaseProgressBlock)progressBlock result:(BaseResultBlock)resultBlock {
    
    //判断网络状态
    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWWAN ||
            status == AFNetworkReachabilityStatusReachableViaWiFi   ) {
            
            [[BaseHttpManager defaultManager] configureRequestSerializer];
            [[BaseHttpManager defaultManager].sessionManager POST:url parameters:parms headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                int i = 0;
                for (UIImage *image in imageList) {
                    NSString *fileName = [NSString stringWithFormat:@"%d.png",i];
                    NSData *imageData;
                    imageData = UIImageJPEGRepresentation(image, 1.0f);
                    [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
                    i++;
                    NSLog(@"  ----------------------  %lu",(unsigned long)imageData.length);
                }
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                if (progressBlock) {
                    progressBlock(uploadProgress);
                }
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [self requestLog:task parms:parms responseObject:responseObject error:nil];
                resultBlock(responseObject,nil);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self requestLog:task parms:parms responseObject:nil error:error];
                resultBlock(nil,error);
            }];
        }else {
            
        }
    }];

}

+ (void)basePOST:(NSString *)url cache:(BOOL)cache audioFile:(NSString *)filePath autoHideLoading:(BOOL)hide parms:(id)parms result:(BaseResultBlock)resultBlock {
    
    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) {
            [[BaseHttpManager defaultManager] configureRequestSerializer];
           // NSDictionary *header = lApp.useModel.token?@{@"token":lApp.useModel.token} :nil;
            [[BaseHttpManager defaultManager].sessionManager POST:url parameters:parms headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                NSString *name = [NSString stringWithFormat:@"%f_recording.mp3",[[NSDate date] timeIntervalSince1970]];
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath]
                                               name:@"file"
                                           fileName:name
                                           mimeType:@"audio/mp3"
                                              error:nil];
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self requestLog:task parms:parms responseObject:responseObject error:nil];
                resultBlock(responseObject,nil);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self requestLog:task parms:parms responseObject:nil error:error];
                resultBlock(nil,error);
            }];
        }else {
            
        }
    }];
    
}


#pragma mark --- 检测网络状态
+ (void)checkoutNetWorkStatus:(void(^)(AFNetworkReachabilityStatus status))block {
   
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        block(status);
    }];
    [manager startMonitoring];
}

/// 打印数据
+ (void)requestLog:(id)task parms:(id)parms responseObject:(id)responseObject error:(NSError *)error {
    
    if (KMRequestOpenLog) {
        
        if ([task isKindOfClass:[NSURLSessionDataTask class]]) {
            DebugLog(@"请求地址：%@",((NSURLSessionDataTask*)task).currentRequest.URL.absoluteString);
        }
        else if ([task isKindOfClass:[NSURLResponse class]]) {
            DebugLog(@"请求地址：%@",((NSURLResponse*)task).URL.absoluteString);
        }
        if (parms) {
            DebugLog(@"请求参数：%@",parms);
        }
        if (responseObject) {
            DebugLog(@"服务器返回数据：%@",responseObject);
        }
        if (error) {
            DebugLog(@"Error结果：%@",error);
        }
    }
}

@end
